
/**
 * Created by dwj on 2020/12/24.
 * @description indexedDB 数据库操作 
 * @description 与cache的区别：cache是对memory,cache,indexdb 三种缓存策略的集成
 */
 Rsd.define('Rsd.data.IndexedDB', {
    extend: 'Rsd.common.Object',
    xtype:'indexedDB', 
    /*
    * 数据库
    * */
    //database:null,  
    objectStores:[],
    /*
    *
    * */
    constructor: function indexedDB(config) {
        config = config || {};
        this.apply(config);
    },
    /**
     * 打开数据库
     * 第一个参数databaseName 是字符串，表示数据库的名字。如果指定的数据库不存在，就会新建数据库。
     * 第二个参数version 是整数，表示数据库的版本,如果省略，打开已有数据库时，默认为当前版本；新建数据库时，默认为1
     */
    openDB:function openDB(databaseName, version)
    {
        var me = this;
        me.databaseName = databaseName;

        this.__request = window.indexedDB.open(databaseName, version||Date.now());
        this.__request.onerror = function (event) {
            console.log('数据库打开报错',event);
          };

          this.__request.onsuccess = function (event) {
            me.database =  me.__request.result;
            //console.log('数据库打开成功',event);
          };
  
          //如果指定的版本号（version），大于数据库的实际版本号，就会发生数据库升级事件upgradeneeded。
          this.__request.onupgradeneeded = function (event) { 
            
            var db = event.target.result;
          
            var _objectStores =  me.objectStores||[];

            _objectStores.forEach(function(item){
                if(db.objectStoreNames.contains(item.name))
                {
                    return;
                }
                var objectStore = db.createObjectStore(item.name, {keyPath: item.keyName ,autoIncrement:item.autoIncrement});

                var _indexs = item.indexs ||[];
                _indexs.forEach(function(indexItem){
                    objectStore.createIndex(indexItem.name, indexItem.name, { unique: indexItem.unique });
                });
               
            });
             
            //console.log('数据库升级',event);
          };
    },
    /**
     * 关闭数据库
     */
    closeDB:function closeDB(){
        this.database.close();
    },
    /**
     * 删除数据库
     */
    deleteDB:function deleteDB(){

        window.indexedDB.deleteDatabase(this.databaseName);
        me.database = null;
    },
 
   
    /**
     * 添加数据
     * @param {*} objectStoreName 
     * @param {*} data 
     */
    addObject:function addObject(objectStoreName,data) {
        var me= this;
        var objectStore = null;
        if(objectStoreName instanceof IDBObjectStore )
        {
            objectStore = objectStoreName;
        }
        else
        {
            if(me.database)
            {
                var db = me.database;
                var transaction = db.transaction([objectStoreName], 'readwrite');
                var objectStore = transaction.objectStore(objectStoreName);
            }
            else
            {
                console.log('数据库创建中...');
            }
            
             
        }
       
        var request =  objectStore.add(data);
      
        request.onsuccess = function (event) {
          //console.log('数据写入成功',event);
        };
      
        request.onerror = function (event) {
          console.log('数据写入失败',event);
        }
    },

    /**
     * 更新数据
     * @param {*} objectStoreName 
     * @param {*} data 
     */        
    updateObject:function updateObject(objectStoreName,data)
    {
        var me= this;
        var db = me.database;
        var request = db.transaction([objectStoreName], 'readwrite').objectStore(objectStoreName).put(data);

            request.onsuccess = function (event) {
                //console.log('数据更新成功',event);
            };

            request.onerror = function (event) {
                console.log('数据更新失败',event);
            }    
    },

    /**
     * 通过键值获取数据
     * @param {*} objectStoreName 
     * @param {*} keyValue 
     */
    getObjectByKey:function getObjectByKey(objectStoreName,keyValue,callback) {

        var me= this;
        var objectStore = null;
        if(objectStoreName instanceof IDBObjectStore )
        {
            objectStore = objectStoreName;
        }
        else
        {
            if(me.database)
            {
                var db = me.database;
                try
                {
                    var transaction = db.transaction([objectStoreName]);
                    objectStore = transaction.objectStore(objectStoreName);
                }
                catch(err)
                {
                    console.error(objectStoreName,err);
                }
            }
            else
            {
                console.log('数据库创建中...');
            }
            
            
        }
       
        if(objectStore==null)
        {
            return;
        }
        var request = objectStore.get(keyValue);
     
        request.onerror = function(event) {
            if(callback)
            {
              callback(null);
              return;
            }
           //console.log('事务失败',event);
        };
     
        request.onsuccess = function(event) {

            if(callback)
            {
              callback(request.result);
              return;
            }

           //if (request.result) 
           //{
           //  console.log('数据记录', request.result);
           //} 
           //else 
           //{
           //  console.log('未获得数据记录');
           //}

        };
     },
    
     /**
      * 通过索引获取数据
      * @param {*} objectStoreName 
      * @param {*} key 
      */
     getObjectByIndex:function getObjectByIndex(objectStoreName,indexName,indexValue,callback) {
        var me= this;
        var objectStore = null;
        if(objectStoreName instanceof IDBObjectStore )
        {
            objectStore = objectStoreName;
        }
        else
        {
            if(me.database)
            {
                var db = me.database;
                var transaction = db.transaction([objectStoreName]);
                objectStore = transaction.objectStore(objectStoreName);
            } 
            else
            {
                console.log('数据库创建中...');
            }
        }
        var index = objectStore.index(indexName);
        var request = index.get(indexValue);
       
        request.onerror = function(event) {
            if(callback)
            {
              callback(null);
              return;
            }
            console.log('事务失败',event);
        };
     
        request.onsuccess = function( event) {
            if(callback)
            {
              callback(null);
              return;
            }

           if (request.result) {
              console.log('数据记录' + request.result);
           } 
           else 
           {
              console.log('未获得数据记录');
           }
        };
     },

     /**
      * 遍历数据
      * @param {*} objectStoreName 
      */
     listObject:function listObject(objectStoreName)
     {
        var me= this;
        var objectStore = null;
        if(objectStoreName instanceof IDBObjectStore )
        {
            objectStore = objectStoreName;
        }
        else
        {
            if(me.database)
            {
                var db = me.database;
                objectStore = db.transaction([objectStoreName]).objectStore(objectStoreName);
                objectStore.openCursor().onsuccess = function (event) {
                    var cursor = event.target.result;
             
                    if (cursor)
                    {
                        console.log(cursor);
                        cursor.continue();
                    } 
                    else 
                    {
                        console.log('没有更多数据了！');
                    }
               };
            }
            else
            {
                console.log('数据库创建中...');
            }
            
        }
       
       
     },
     
     /**
      * 删除数据
      * @param {*} objectStoreName 
      * @param {*} keyValue 
      */
     deleteObject:function deleteObject(objectStoreName,keyValue)
     {
        var me= this;
        var db = me.database;
        if(me.database)
        {
            var request = db.transaction([objectStoreName], 'readwrite')
            .objectStore(objectStoreName)
            .delete(keyValue);
        
            request.onsuccess = function (event) {
                console.log('数据删除成功',event);
            };
        }
        else
        {
            console.log('数据库创建中...');
        }
        
     } 
 

},function(type){
    
    var _databaseGetter = function () {
 
        return this.__database;
    };

    var _databaseSetter = function (value) {
        this.__database =value;
    };
    this.defineProperty(type,"database", _databaseGetter, _databaseSetter,false);
});